package com.charles.video.common.core.utils;

import com.charles.video.common.core.responseDomain.PageDomain;
import com.charles.video.common.core.responseDomain.TableSupport;
import com.github.pagehelper.PageHelper;

import java.util.Collections;
import java.util.List;


/**
 * 分页工具类
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 手动分页
     */
    public static List<?> startPage(List<?> list, Integer pageNum, Integer pageSize) {
        if (list == null || list.isEmpty()) return Collections.emptyList();

        Integer count = list.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, count);
        if (fromIndex + 1 > count) return Collections.emptyList();
        return list.subList(fromIndex, toIndex);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }
}
